<template>
  <a-row class="w-full h-full flex flex-col overflow-auto px-2 sm:px-4 md:px-6 lg:px-8 py-4">
      <!-- 表单内容区域 -->
      <a-row class="w-full flex-1">
        <!-- 涉案物入(出)库清单 -->
        <div class="text-xl font-bold text-center py-4 mb-6 text-primary border-b border-gray-200 bg-gray-50 rounded-t-lg">涉案物入(出)库清单</div>
        
        <!-- 案件基本信息 -->
        <a-form :model="caseBaseInfo" layout="vertical" class="mb-8 p-4 bg-white rounded-lg shadow-sm">
          <div class="text-lg font-bold mb-4">案件基本信息</div>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item field="caseName" label="案件名称" required>
                <a-input v-model="caseBaseInfo.caseName" placeholder="请输入案件名称" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="caseNature" label="涉案性质" required>
                <a-input v-model="caseBaseInfo.caseNature" placeholder="请输入涉案性质" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="filingTime" label="立案时间" required>
                <a-date-picker v-model="caseBaseInfo.filingTime" style="width: 100%" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item field="forceMeasureStartTime" label="行政强制措施开始时间">
                <a-date-picker v-model="caseBaseInfo.forceMeasureStartTime" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="forceMeasureEndTime" label="行政强制措施结束时间">
                <a-date-picker v-model="caseBaseInfo.forceMeasureEndTime" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="forceMeasureStage" label="行政强制措施">
                <a-input v-model="caseBaseInfo.forceMeasureStage" placeholder="请输入行政强制措施中台" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item field="party" label="当事人">
                <a-input v-model="caseBaseInfo.party" placeholder="请输入当事人" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="caseHandler" label="案件经办人员" required>
                <a-input v-model="caseBaseInfo.caseHandler" placeholder="请输入案件经办人员" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="unit" label="单位" required>
                <a-input v-model="caseBaseInfo.unit" placeholder="请输入单位" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item field="serialNo" label="编号" required>
                <a-input v-model="caseBaseInfo.serialNo" placeholder="请输入编号" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>

        <!-- 涉案物品清单（多条记录） -->
        <a-form layout="vertical" class="mb-8 p-4 bg-white rounded-lg shadow-sm">
          <div class="flex justify-between items-center mb-4">
            <div class="text-lg font-bold">涉案物品清单</div>
            <a-button type="primary" size="small" @click="addItem">
              <template #icon>
                <icon-plus />
              </template>
              添加物品
            </a-button>
          </div>
          
          <a-table :columns="itemColumns" :data="caseItems" :pagination="false" bordered>
            <template #operation="{ record, rowIndex }">
              <a-button type="text" status="danger" @click="removeItem(rowIndex)">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
            </template>
            
            <template #itemName="{ record, rowIndex }">
              <a-input v-model="caseItems[rowIndex].itemName" placeholder="请输入物品名称" />
            </template>
            
            <template #brand="{ record, rowIndex }">
              <a-input v-model="caseItems[rowIndex].brand" placeholder="请输入品牌" />
            </template>
            
            <template #model="{ record, rowIndex }">
              <a-input v-model="caseItems[rowIndex].model" placeholder="请输入规格型号" />
            </template>
            
            <template #totalQuantity="{ record, rowIndex }">
              <a-input-number v-model="caseItems[rowIndex].totalQuantity" placeholder="请输入总数量" style="width: 100%" />
            </template>
            
            <template #newQuantity="{ record, rowIndex }">
              <a-input-number v-model="caseItems[rowIndex].newQuantity" placeholder="请输入新品数量" style="width: 100%" />
            </template>
            
            <template #usedQuantity="{ record, rowIndex }">
              <a-input-number v-model="caseItems[rowIndex].usedQuantity" placeholder="请输入旧品数量" style="width: 100%" />
            </template>
            
            <template #inboundTime="{ record, rowIndex }">
              <a-date-picker v-model="caseItems[rowIndex].inboundTime" style="width: 100%" show-time />
            </template>
            
            <template #outboundTime="{ record, rowIndex }">
              <a-date-picker v-model="caseItems[rowIndex].outboundTime" style="width: 100%" show-time />
            </template>
            
            <template #forceMeasureDocNo="{ record, rowIndex }">
              <a-input v-model="caseItems[rowIndex].forceMeasureDocNo" placeholder="请输入文书文号" />
            </template>
            
            <template #punishmentDocNo="{ record, rowIndex }">
              <a-input v-model="caseItems[rowIndex].punishmentDocNo" placeholder="请输入文书文号" />
            </template>
            
            <template #caseHandlers="{ record, rowIndex }">
              <a-space direction="vertical" style="width: 100%">
                <a-input v-model="caseItems[rowIndex].caseHandler1" placeholder="办案人员1" />
                <a-input v-model="caseItems[rowIndex].caseHandler2" placeholder="办案人员2" />
              </a-space>
            </template>
            
            <template #warehouseKeeper="{ record, rowIndex }">
              <a-input v-model="caseItems[rowIndex].warehouseKeeper" placeholder="请输入仓管员姓名" />
            </template>
            
            <template #images="{ record, rowIndex }">
              <div class="w-full">
                <a-upload
                  list-type="picture-card"
                  :file-list="caseItems[rowIndex].images"
                  @change="(fileList) => handleImageChange(fileList, rowIndex)"
                  multiple
                  :custom-request="customUploadRequest"
                >
                  <div class="arco-upload-trigger-picture">
                    <div class="arco-upload-trigger-picture-text">
                      <icon-plus />
                      <div>上传图片</div>
                    </div>
                  </div>
                </a-upload>
              </div>
            </template>
          </a-table>
        </a-form>

        <!-- 监察记录（多条记录） -->
        <a-form layout="vertical" class="mb-8 p-4 bg-white rounded-lg shadow-sm">
          <div class="flex justify-between items-center mb-4">
            <div class="text-lg font-bold">监察记录</div>
            <a-button type="primary" size="small" @click="addSupervision">
              <template #icon>
                <icon-plus />
              </template>
              添加记录
            </a-button>
          </div>
          
          <a-table :columns="supervisionColumns" :data="supervisions" :pagination="false" bordered>
            <template #operation="{ record, rowIndex }">
              <a-button type="text" status="danger" @click="removeSupervision(rowIndex)">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
            </template>
            
            <template #supervisionTime="{ record, rowIndex }">
              <a-date-picker v-model="supervisions[rowIndex].supervisionTime" style="width: 100%" show-time />
            </template>
            
            <template #supervisionLocation="{ record, rowIndex }">
              <a-input v-model="supervisions[rowIndex].supervisionLocation" placeholder="请输入地点" />
            </template>
            
            <template #supervisionReason="{ record, rowIndex }">
              <a-input v-model="supervisions[rowIndex].supervisionReason" placeholder="请输入监察事由" />
            </template>
            
            <template #documentBasis="{ record, rowIndex }">
              <a-input v-model="supervisions[rowIndex].documentBasis" placeholder="请输入文书依据" />
            </template>
            
            <template #operator="{ record, rowIndex }">
              <a-input v-model="supervisions[rowIndex].operator" placeholder="请输入经办人" />
            </template>
            
            <template #warehouseKeeper="{ record, rowIndex }">
              <a-input v-model="supervisions[rowIndex].warehouseKeeper" placeholder="请输入仓管员" />
            </template>
            
            <template #supervisor="{ record, rowIndex }">
              <a-input v-model="supervisions[rowIndex].supervisor" placeholder="请输入监察员" />
            </template>
          </a-table>
        </a-form>

        <!-- 人员进出仓库登记簿（多条记录） -->
        <div class="text-xl font-bold text-center py-4 mb-6 text-primary border-b border-gray-200 bg-gray-50 rounded-t-lg">人员进出仓库登记簿</div>
        <a-form layout="vertical" class="mb-8 p-4 bg-white rounded-lg shadow-sm">
          <div class="flex justify-between items-center mb-4">
            <div class="text-lg font-bold">人员进出记录</div>
            <a-button type="primary" size="small" @click="addPersonnelRegister">
              <template #icon>
                <icon-plus />
              </template>
              添加记录
            </a-button>
          </div>
          
          <a-table :columns="personnelRegisterColumns" :data="personnelRegisters" :pagination="false" bordered>
            <template #operation="{ record, rowIndex }">
              <a-button type="text" status="danger" @click="removePersonnelRegister(rowIndex)">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
            </template>
            
            <template #personnel="{ record, rowIndex }">
              <a-input v-model="personnelRegisters[rowIndex].personnel" placeholder="请输入出入人员" />
            </template>
            
            <template #reason="{ record, rowIndex }">
              <a-input v-model="personnelRegisters[rowIndex].reason" placeholder="请输入出入事由" />
            </template>
            
            <template #inboundTime="{ record, rowIndex }">
              <a-date-picker v-model="personnelRegisters[rowIndex].inboundTime" style="width: 100%" show-time />
            </template>
            
            <template #outboundTime="{ record, rowIndex }">
              <a-date-picker v-model="personnelRegisters[rowIndex].outboundTime" style="width: 100%" show-time />
            </template>
            
            <template #remarks="{ record, rowIndex }">
              <a-textarea v-model="personnelRegisters[rowIndex].remarks" placeholder="请输入备注" />
            </template>
          </a-table>
        </a-form>
      </a-row>

      <!-- 分割线 -->
      <a-divider class="my-4"/>

      <!-- 按钮操作区 -->
      <a-row class="w-full my-6" justify="center">
        <a-space size="large">
          <a-button size="large" @click="cancelForm">取消</a-button>
          <a-button size="large" type="primary" @click="submitForm">提交</a-button>
        </a-space>
      </a-row>
    </a-row>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';

// 加载状态
const spinLoading = ref(false);

// 接收父组件参数
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  }
});

// 父组件函数
const emits = defineEmits(['ok', 'cancel']);

// 案件基本信息
const caseBaseInfo = reactive({
  caseName: '',
  caseNature: '',
  filingTime: null,
  forceMeasureStartTime: null,
  forceMeasureEndTime: null,
  forceMeasureStage: '',
  party: '',
  caseHandler: '',
  unit: '',
  serialNo: ''
});

// 涉案物品清单（多条记录）
const caseItems = ref([]);

// 监察记录（多条记录）
const supervisions = ref([]);

// 人员进出仓库登记簿（多条记录）
const personnelRegisters = ref([]);

// 人员进出仓库登记簿表格列定义
const personnelRegisterColumns = [
  {
    title: '出入人员',
    slotName: 'personnel',
    width: 150,
    align: 'center'
  },
  {
    title: '出入事由',
    slotName: 'reason',
    width: 200,
    align: 'center'
  },
  {
    title: '入库时间',
    slotName: 'inboundTime',
    width: 220,
    align: 'center'
  },
  {
    title: '出库时间',
    slotName: 'outboundTime',
    width: 220,
    align: 'center'
  },
  {
    title: '备注',
    slotName: 'remarks',
    width: 250,
    align: 'center'
  },
  {
    title: '操作',
    slotName: 'operation',
    width: 80,
    align: 'center'
  }
];

// 涉案物品清单表格列定义
const itemColumns = [
  {
    title: '物品名称',
    slotName: 'itemName',
    width: 150,
    align: 'center'
  },
  {
    title: '品牌',
    slotName: 'brand',
    width: 120,
    align: 'center'
  },
  {
    title: '规格型号',
    slotName: 'model',
    width: 120,
    align: 'center'
  },
  {
    title: '总数量',
    slotName: 'totalQuantity',
    width: 100,
    align: 'center'
  },
  {
    title: '新品数量',
    slotName: 'newQuantity',
    width: 100,
    align: 'center'
  },
  {
    title: '旧品数量',
    slotName: 'usedQuantity',
    width: 100,
    align: 'center'
  },
  {
    title: '入库时间',
    slotName: 'inboundTime',
    width: 220,
    align: 'center'
  },
  {
    title: '出库时间',
    slotName: 'outboundTime',
    width: 220,
    align: 'center'
  },
  {
    title: '强制措施文号',
    slotName: 'forceMeasureDocNo',
    width: 220,
    align: 'center'
  },
  {
    title: '处罚决定书文号',
    slotName: 'punishmentDocNo',
    width: 220,
    align: 'center'
  },
  {
    title: '办案人员',
    slotName: 'caseHandlers',
    width: 150,
    align: 'center'
  },
  {
    title: '仓管员',
    slotName: 'warehouseKeeper',
    width: 120,
    align: 'center'
  },
  {
    title: '物品图片',
    slotName: 'images',
    width: 200,
    align: 'center'
  },
  {
    title: '操作',
    slotName: 'operation',
    width: 80,
    align: 'center'
  }
];

// 监察记录表格列定义
const supervisionColumns = [
  {
    title: '监察时间',
    slotName: 'supervisionTime',
    width: 220,
    align: 'center'
  },
  {
    title: '地点',
    slotName: 'supervisionLocation',
    width: 150,
    align: 'center'
  },
  {
    title: '监察事由',
    slotName: 'supervisionReason',
    width: 150,
    align: 'center'
  },
  {
    title: '文书依据',
    slotName: 'documentBasis',
    width: 150,
    align: 'center'
  },
  {
    title: '经办人',
    slotName: 'operator',
    width: 120,
    align: 'center'
  },
  {
    title: '仓管员',
    slotName: 'warehouseKeeper',
    width: 120,
    align: 'center'
  },
  {
    title: '监察员',
    slotName: 'supervisor',
    width: 120,
    align: 'center'
  },
  {
    title: '操作',
    slotName: 'operation',
    width: 80,
    align: 'center'
  }
];

// 添加物品记录
const addItem = () => {
  caseItems.value.push({
    itemName: '',
    brand: '',
    model: '',
    totalQuantity: null,
    newQuantity: null,
    usedQuantity: null,
    inboundTime: null,
    forceMeasureDocNo: '',
    outboundTime: null,
    punishmentDocNo: '',
    caseHandler1: '',
    caseHandler2: '',
    warehouseKeeper: '',
    // 添加图片字段，用于存储图片列表
    images: []
  });
};

// 删除物品记录
const removeItem = (index) => {
  caseItems.value.splice(index, 1);
};

// 添加监察记录
const addSupervision = () => {
  supervisions.value.push({
    supervisionTime: null,
    supervisionLocation: '',
    supervisionReason: '',
    documentBasis: '',
    operator: '',
    warehouseKeeper: '',
    supervisor: ''
  });
};

// 删除监察记录
const removeSupervision = (index) => {
  supervisions.value.splice(index, 1);
};

// 添加人员进出记录
const addPersonnelRegister = () => {
  personnelRegisters.value.push({
    personnel: '',
    reason: '',
    inboundTime: null,
    outboundTime: null,
    remarks: ''
  });
};

// 删除人员进出记录
const removePersonnelRegister = (index) => {
  personnelRegisters.value.splice(index, 1);
};

// 提交表单
const submitForm = () => {
  // 表单验证逻辑
  if (!caseBaseInfo.caseName) {
    // 显示错误提示
    return;
  }
  
  // 检查物品清单是否为空
  if (caseItems.value.length === 0) {
    // 显示错误提示：请至少添加一条物品记录
    return;
  }
  
  // 检查每条物品记录的必填字段
  for (let i = 0; i < caseItems.value.length; i++) {
    const item = caseItems.value[i];
    if (!item.itemName || !item.totalQuantity || !item.inboundTime) {
      // 显示错误提示：请完善第 ${i+1} 条物品记录的必填信息
      return;
    }
  }
  
  // 检查监察记录的必填字段
  for (let i = 0; i < supervisions.value.length; i++) {
    const supervision = supervisions.value[i];
    if (!supervision.supervisionTime || !supervision.supervisionLocation || !supervision.supervisionReason) {
      // 显示错误提示：请完善第 ${i+1} 条监察记录的必填信息
      return;
    }
  }
  
  // 检查人员进出仓库登记簿是否为空
  if (personnelRegisters.value.length === 0) {
    // 显示错误提示：请至少添加一条人员进出记录
    Message.error('请至少添加一条人员进出记录');
    return;
  }
  
  // 检查每条人员进出记录的必填字段
  for (let i = 0; i < personnelRegisters.value.length; i++) {
    const register = personnelRegisters.value[i];
    if (!register.personnel || !register.reason || !register.inboundTime) {
      // 显示错误提示：请完善第 ${i+1} 条人员进出记录的必填信息
      Message.error(`请完善第 ${i+1} 条人员进出记录的必填信息`);
      return;
    }
  }
  
  // 组装提交数据
  const submitData = {
    caseBaseInfo: { ...caseBaseInfo },
    caseItems: [...caseItems.value],
    supervisions: [...supervisions.value],
    personnelRegisters: [...personnelRegisters.value]
  };
  
  console.log('提交数据:', submitData);
  
  // 提交成功后通知父组件
  emits('ok');
};

// 取消操作
const cancelForm = () => {
  emits('cancel');
};

// 重置表单
const resetForm = () => {
  // 重置案件基本信息
  Object.keys(caseBaseInfo).forEach(key => {
    if (typeof caseBaseInfo[key] === 'string') {
      caseBaseInfo[key] = '';
    } else {
      caseBaseInfo[key] = null;
    }
  });

  // 重置涉案物品清单
  caseItems.value = [];

  // 重置监察记录
  supervisions.value = [];

  // 重置人员进出仓库登记簿
  personnelRegisters.value = [];
};

// 自定义上传请求处理函数
const customUploadRequest = (options) => {
  const { onProgress, onSuccess, onError, fileItem } = options;
  
  // 模拟上传进度
  const interval = setInterval(() => {
    const percent = Math.floor(Math.random() * 10) + 10;
    onProgress(percent);
  }, 300);
  
  // 模拟上传完成
  setTimeout(() => {
    clearInterval(interval);
    onProgress(100);
    
    // 模拟服务器返回的文件URL
    const response = {
      url: URL.createObjectURL(fileItem.file),
      name: fileItem.file.name,
      uid: fileItem.uid
    };
    
    onSuccess(response);
  }, 1500);
};

// 页面加载时初始化数据
onMounted(() => {
  // 加载数据
  loadData();
  
  // 如果是新建模式，添加一条空的人员进出记录
  if (!props.params || props.params.operationType !== 'update') {
    addPersonnelRegister();
  }
});

// 处理图片变更
const handleImageChange = (fileList, rowIndex) => {
  // 更新对应行的图片列表
  caseItems.value[rowIndex].images = fileList;
};

// 加载数据
const loadData = () => {
  // 如果是编辑模式，加载数据
  if (props.params && props.params.operationType === 'update' && props.params.id) {
    spinLoading.value = true;
    // 模拟API请求延迟
    setTimeout(() => {
      // 模拟数据 - 实际应用中应该通过API获取
      if (props.params.id === 1) {
        // 添加人员进出记录示例数据
        personnelRegisters.value = [
          {
            personnel: '李某某',
            reason: '检查涉案物品',
            inboundTime: new Date('2023-01-15 09:30:00'),
            outboundTime: new Date('2023-01-15 11:00:00'),
            remarks: '例行检查'
          },
          {
            personnel: '王某某',
            reason: '取证',
            inboundTime: new Date('2023-01-20 14:00:00'),
            outboundTime: new Date('2023-01-20 16:30:00'),
            remarks: '取证拍照'
          }
        ];
        // 填充案件基本信息
        caseBaseInfo.caseName = '某违法建筑案';
        caseBaseInfo.caseNature = '违法建筑';
        caseBaseInfo.filingTime = new Date('2022-12-25');
        caseBaseInfo.forceMeasureStartTime = new Date('2023-01-01');
        caseBaseInfo.forceMeasureEndTime = new Date('2023-02-01');
        caseBaseInfo.forceMeasureStage = '调查取证';
        caseBaseInfo.party = '张某某';
        caseBaseInfo.caseHandler = '张三、李四';
        caseBaseInfo.unit = '市执法局';
        caseBaseInfo.serialNo = 'BH-2023-001';
        
        // 填充涉案物品清单（多条记录）
        caseItems.value = [
          {
            itemName: '建筑材料',
            brand: 'XX品牌',
            model: 'A型号',
            totalQuantity: 100,
            newQuantity: 80,
            usedQuantity: 20,
            inboundTime: new Date('2023-01-01 10:00:00'),
            forceMeasureDocNo: 'XZQZ-2023-001',
            outboundTime: new Date('2023-02-01 14:00:00'),
            punishmentDocNo: 'XZCF-2023-001',
            caseHandler1: '张三',
            caseHandler2: '李四',
            warehouseKeeper: '王五',
            images: [
              {
                uid: '1',
                name: '建筑材料图片1.jpg',
                url: 'https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
              },
              {
                uid: '2',
                name: '建筑材料图片2.jpg',
                url: 'https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/e278888093bef8910e829486fb45dd69.png~tplv-uwbnlip3yd-webp.webp'
              }
            ]
          },
          {
            itemName: '电动工具',
            brand: 'YY品牌',
            model: 'B型号',
            totalQuantity: 50,
            newQuantity: 30,
            usedQuantity: 20,
            inboundTime: new Date('2023-01-02 11:00:00'),
            forceMeasureDocNo: 'XZQZ-2023-002',
            outboundTime: null,
            punishmentDocNo: '',
            caseHandler1: '张三',
            caseHandler2: '李四',
            warehouseKeeper: '王五',
            images: [
              {
                uid: '3',
                name: '电动工具图片.jpg',
                url: 'https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/3ee5f13fb09879ecb5185e440cef6eb9.png~tplv-uwbnlip3yd-webp.webp'
              }
            ]
          }
        ];
        
        // 填充监察记录（多条记录）
        supervisions.value = [
          {
            supervisionTime: new Date('2023-01-15 09:00:00'),
            supervisionLocation: '市执法局仓库',
            supervisionReason: '例行检查',
            documentBasis: 'WS-2023-001',
            operator: '赵六',
            warehouseKeeper: '王五',
            supervisor: '钱七'
          },
          {
            supervisionTime: new Date('2023-01-25 14:00:00'),
            supervisionLocation: '市执法局仓库',
            supervisionReason: '定期检查',
            documentBasis: 'WS-2023-002',
            operator: '赵六',
            warehouseKeeper: '王五',
            supervisor: '钱七'
          }
        ];
        
        // 填充人员进出仓库登记簿表单
        // 先添加一条记录
        addPersonnelRegister();
        personnelRegisters.value[0].personnel = '张三、李四';
        personnelRegisters.value[0].reason = '取证检查';
        personnelRegisters.value[0].inboundTime = new Date('2023-01-15 09:00:00');
        personnelRegisters.value[0].outboundTime = new Date('2023-01-15 11:00:00');
        personnelRegisters.value[0].remarks = '正常检查';
      }
      spinLoading.value = false;
    }, 500);
  } else {
    // 如果是新增模式，初始化一条空的物品记录和监察记录
    addItem();
    addSupervision();
  }
};

// 初始化
onMounted(() => {
  loadData();
});
</script>